#include <iostream>
#include <set>

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>

#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <pthread.h>

using namespace std;

set<string> file_list;

void scan_file()
{
    char szPid[32];
    snprintf(szPid, sizeof(szPid), "%d", getpid());
    while(1)
    {
        DIR *dir;
        struct dirent *dirp;

        dir = opendir("./tmp");
        if(dir == NULL)
        {
            perror("opendir");
            return;
        }

        while((dirp = readdir(dir)) != NULL)
        {
            if(strcmp(dirp->d_name, ".") == 0 || strcmp(dirp->d_name, "..") == 0)
            {
                continue;
            }
            if(dirp->d_type == DT_DIR)
            {
                continue;
            }
            if(strcmp(dirp->d_name, szPid) == 0)
            {
                continue;
            }
            file_list.insert(dirp->d_name);
        }
        sleep(1);
    }
}

int main()
{

    pthread_t tid;
    int ret;
    ret = pthread_create(&tid, NULL, (void*(*)(void*))scan_file, NULL);

    key_t key = ftok(".", 1);
    int msgid = msgget(key, IPC_CREAT | 0666);
    long type = getpid();
    char szPid[32];
    snprintf(szPid, sizeof(szPid), "./tmp/%d", type);
    FILE *fp = fopen(szPid, "w");
    fclose(fp);
    
    while(true)
    {
        while(true)
        {
            struct msgbuf msg;
        int ret = msgrcv(msgid, &msg, sizeof(msg), type, IPC_NOWAIT);
        if(ret == -1)
        {
            printf("errorinfo:%s\n", strerror(errno));
            break;
        }
        else
        {
            printf("recive : %s\n", msg.mtext);
        }
        }

        for(auto it = file_list.begin(); it != file_list.end(); it++)
        {
            struct msgbuf sndmsg;
            sndmsg.mtype = atoi(it->c_str());
            snprintf(sndmsg.mtext, 1024, "hello i am %d", getpid());
            msgsnd(msgid, &sndmsg, sizeof(sndmsg), 0);
        }
        sleep(5);
    }
    ret = pthread_join(tid, NULL);
    if(ret)
    {
        perror("pthread_join");
    }
    return 0;
}
